package tgc.edu.ljc.layui.web.controller;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import tgc.edu.ljc.layui.entity.Admin;
import tgc.edu.ljc.layui.entity.SysRole;
import tgc.edu.ljc.layui.entity.SysUser;
import tgc.edu.ljc.layui.security.UserUtils;
import tgc.edu.ljc.layui.service.AdminService;
import tgc.edu.ljc.layui.service.RoleService;
import tgc.edu.ljc.layui.service.SysUserService;

@Controller
public class MainController {
	@Autowired
	private SysUserService userService;
	@Autowired
	private UserUtils userUtils;
	@Autowired
	private RoleService roleService;
	@Autowired
	private AdminService adminService;
	
	
	@RequestMapping(value= {"/main","/"})
	public String first() {
		return "first";
	}
	
	@RequestMapping(value= "/login",method=RequestMethod.GET)
	public String gotoLogin() {
		List<SysRole> roles = roleService.findAll();
		if(roles.isEmpty()) {
			SysRole role1=new SysRole();
			role1.setName("管理员");
			role1.setCode("ROLE_ADMIN");
			roleService.save(role1);
			SysRole role2=new SysRole();
			role2.setCode("ROLE_STUDENT");
			role2.setName("学生");
			roleService.save(role2);
			Admin admin=new Admin();
			admin.setName("陈老师");
			admin.setJob("教师");
			admin.setUsername("admin");
			BCryptPasswordEncoder encoder=new BCryptPasswordEncoder();
			admin.setPassword(encoder.encode("admin"));
			admin.getRoles().add(role1);
			adminService.save(admin);
		}
		return "login";
	}
	
	@RequestMapping(value="/changePwd")
	public String changePwd() {
		return "changePwd";
	}
	
	@RequestMapping(value="/changePassword",method=RequestMethod.POST)
	public String changePassword(String oldPwd,String newPwd) {
		BCryptPasswordEncoder encoder = new BCryptPasswordEncoder();
		SysUser user = userUtils.getUser();
		String password = user.getPassword();
		if(encoder.matches(oldPwd, password)) {
			user.setPassword(encoder.encode(newPwd));
			userService.save(user);
		}
		return "redirect:logout";
	}
}
